package com.iqiyi.pps.epg.core.service.sginal;

import com.iqiyi.pps.epg.api.model.web.query.TFilter;
import com.iqiyi.pps.epg.api.model.web.query.TPage;
import com.iqiyi.pps.epg.api.model.web.sginal.TServer;
import com.iqiyi.pps.epg.api.model.web.sginal.TServerDataPage;
import com.iqiyi.pps.epg.core.dao.base.Page;
import com.iqiyi.pps.epg.core.dao.base.PropertyFilter;
import com.iqiyi.pps.epg.core.dao.record.RecordChannelSignalDao;
import com.iqiyi.pps.epg.core.dao.sginal.ServerClusterDataDao;
import com.iqiyi.pps.epg.core.dao.sginal.ServerDataDao;
import com.iqiyi.pps.epg.core.model.sginal.Server;
import com.iqiyi.pps.epg.core.model.sginal.ServerCluster;
import com.iqiyi.pps.epg.core.utils.TransUtil;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * Created by zhang on 2017/4/28.
 */
@Service
@Transactional
public class ServerServiceImpl implements ServerService {

    @Autowired
    private ServerDataDao dao;

    @Autowired
    private ServerClusterDataDao serverClusterDataDao;

    @Autowired
    private RecordChannelSignalDao recordChannelSignalDao;

    @Override
    public Server get(int id) {
        Server server = dao.get(id);
        return server;
    }

    @Override
    public Server getZzdByInsideIp(String insideServerIp) {
        Criteria criteria = dao.createCriteria();
        criteria.add(Restrictions.eq("insideServerIp", insideServerIp));
        criteria.add(Restrictions.eq("serverType", Server.STATUS_ZZD));
        List<Server> servers = dao.find(criteria);
        return servers.size()>0?servers.get(0):null;
    }

    @Override
    public int add(Server entity) {
        dao.saveOnly(entity);
        return entity.getId();
    }

    @Override
    public void update(Server entity) {
        dao.save(entity);
    }

    @Override
    public boolean checkByServerIp(String insideServerIp, Integer id) {
        Criteria criteria = dao.createCriteria();
        criteria.add(Restrictions.eq("insideServerIp", insideServerIp));
        criteria.add(Restrictions.ne("status", Server.STATUS_IS_DELETE));
        if (id != null) {
            criteria.add(Restrictions.ne("id", id));
        }
        List<Server> servers = dao.find(criteria);
        return servers!= null && servers.size() > 0;
    }

    @Override
    public boolean checkBySn(String sn, Integer id) {
        Criteria criteria = dao.createCriteria();
        criteria.add(Restrictions.eq("sn", sn));
        criteria.add(Restrictions.ne("status", Server.STATUS_IS_DELETE));
        if (id != null) {
            criteria.add(Restrictions.ne("id", id));
        }
        List<Server> servers = dao.find(criteria);
        return servers!= null && servers.size() > 0;
    }

    @Override
    public boolean checkInsideServerIp(String insideServerIp) {
        Criteria criteria = dao.createCriteria();
        criteria.add(Restrictions.eq("insideServerIp", insideServerIp));
        criteria.add(Restrictions.ne("status", Server.STATUS_IS_DELETE));
        List<Server> servers = dao.find(criteria);
        return servers!= null && servers.size() > 0;
    }

    @Override
    public int getServerIncluding(String ip) {
        return recordChannelSignalDao.getServerIpSumByServerIp(ip);
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public TServerDataPage getServersData(TPage page, TFilter filter) {
        Map<String, String> map = filter.getFilters();
        String tempPattern = "${PARAMS}";
        String totalPattern = "select COUNT(*)";
        List<PropertyFilter> filterList = TransUtil.builderFilterList(filter);
        String hql = tempPattern + " from Server";
        Page<Server> dbPage = TransUtil.buildPage(page);

        hql = TransUtil.buildQueryStringByPropertyFilter(dbPage, hql, filterList);

        if (dbPage.isAutoCount()) {
            String totalCount = dao.getSession().createQuery(hql.replace(tempPattern, totalPattern)).uniqueResult().toString();
            page.setTotalCount(Long.valueOf(totalCount));
        }

        List result = dao.getSession().createQuery(hql.replace(tempPattern, ""))
                .setMaxResults(dbPage.getPageSize())
                .setFirstResult((dbPage.getPageNo() - 1) * dbPage.getPageSize())
                .list();
        TServerDataPage tServerDataPage = new TServerDataPage();
        tServerDataPage.setTPage(page);
        List<TServer> tServerDatas = new ArrayList<TServer>();
        for(Object obj : result) {
            Server server = (Server) obj;
            int clusterId = server.getCluster();
            if(clusterId!=-1){
                String hql1 = "from ServerCluster where id = "+ clusterId;
                List res = serverClusterDataDao.getSession().createQuery(hql1).list();
                if(res.size()>0){
                    ServerCluster serverCluster = (ServerCluster) res.get(0);
                    server.setClusterName(serverCluster.getName());
                }
            }
            server.setNow_including(recordChannelSignalDao.getServerIpSumByServerIp(server.getInsideServerIp()));
            tServerDatas.add(server.convertThriftModel());
        }
        tServerDataPage.setResult(tServerDatas);
        return tServerDataPage;
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public List<Server> getAll() {
        Criteria criteria = dao.createCriteria();
        criteria.add(Restrictions.ne("status", Server.STATUS_IS_DELETE));
        List<Server> servers = dao.find(criteria);
        return servers;
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public List<Server> getAllZzd() {
        Criteria criteria = dao.createCriteria();
        criteria.add(Restrictions.eq("serverType", Server.STATUS_ZZD));
        criteria.add(Restrictions.ne("status",Server.STATUS_IS_DELETE));
        List<Server> servers = dao.find(criteria);
        return servers;
    }
}
